import { useEffect, useId, useMemo, useRef, useState } from 'react'
import {
  Anchor,
  Button,
  Col,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  message,
  Modal,
  Popover,
  Radio,
  Row,
  Select,
  Space,
  Switch,
  theme,
} from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'

import { Loading } from '@/components/Loading'
import { useFormAllValues } from '@/hooks/hooks'
import { formAutoTrimOnBlur } from '@/utils/utils'
import { getErrorrTypeName, getLogisticsStatusName, getRouteNodeName, getRouteTypeName } from '../../utils'
import { apiAddTplRoute, apiEditTplRoute, apiGetTplRouteDetail } from '../apis'
import { popupSlot } from '../utils'
import { AddChannelModal } from './AddChannelModal'
import { Channels } from './Channels'
import { DynamicField } from './DynamicField'
import { TFormValues, TSendValues } from './interface'
import { createInitialFormValues, textInputFields } from './utils'
import styles from './styles.module.less'

const updatePopup = popupSlot.insert(null)

interface IAddOrEditTplRouteDrawerProps {
  /** 有值则视为编辑 */
  routeId: string | null | undefined
  /** 新增或编辑成功回调 */
  onSuccess?: () => void
}

export const AddOrEditTplRouteDrawer = Object.assign(
  ({ routeId, onSuccess, destroy }: IAddOrEditTplRouteDrawerProps & { destroy: () => void }) => {
    const { token } = theme.useToken()
    const { open, onHide, afterOpenChange } = popupSlot.useAntdPopupAnimation(destroy)

    const [fetching, setFetching] = useState(false)
    const [form] = Form.useForm<TFormValues>()
    const initialFormValues = useMemo(() => createInitialFormValues(null), [])
    const allValues = useFormAllValues(form, initialFormValues)
    const [submitting, setSubmitting] = useState(false)

    const formProps: FormProps<TFormValues> = {
      form,
      scrollToFirstError: { block: 'center', behavior: 'smooth' },
      layout: 'vertical',
      preserve: true,
      initialValues: initialFormValues,
      onBlur: e => formAutoTrimOnBlur({ event: e, form, includeField: textInputFields }),
    }

    const idPrefix = useId()
    const scrollRef = useRef<HTMLDivElement>(null)
    const typeName = routeId ? '编辑' : '添加'
    const actionName = routeId ? '保存' : '添加'

    // 编辑时获取路由模板详情
    useEffect(() => {
      if (!routeId) return
      setFetching(true)
      apiGetTplRouteDetail(routeId)
        .then(res => {
          form.setFieldsValue(createInitialFormValues(res))
        })
        .finally(() => {
          setFetching(false)
        })
    }, [form, routeId])

    const formRender0 = () => {
      return (
        <div className={styles.card}>
          <div className={styles.card_header}>基础信息</div>
          <div className={styles.card_body}>
            <Form {...formProps}>
              <Row gutter={12}>
                <Col span={8}>
                  <Form.Item label="路由节点" name="routeNode" rules={[{ required: true }]}>
                    <Select
                      placeholder="请选择路由节点"
                      options={getRouteNodeName.valueList.map(d => ({ label: getRouteNodeName(d), value: d }))}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="路由编号"
                    tooltip={{
                      icon: (
                        <Popover mouseLeaveDelay={0} content="编号为纯数字" placement="top">
                          <ExclamationCircleOutlined style={{ marginLeft: 4 }} />
                        </Popover>
                      ),
                    }}
                    name="routeNo"
                    rules={[{ required: true }]}
                  >
                    <InputNumber
                      style={{ width: '100%' }}
                      min="0"
                      precision={0}
                      stringMode
                      controls={false}
                      placeholder="请输入路由编号"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="物流状态" name="logisticsStatus" rules={[{ required: true }]}>
                    <Select
                      placeholder="请选择物流状态"
                      options={getLogisticsStatusName.valueList2.map(v => ({
                        label: getLogisticsStatusName(v),
                        value: v,
                      }))}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="路由类型" name="routeType" rules={[{ required: true }]}>
                    <Radio.Group
                      options={getRouteTypeName.valueList.map(v => ({ label: getRouteTypeName(v), value: v }))}
                      onChange={e => {
                        if (e.target.value !== 2) form.setFieldValue('errorType', undefined)
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="异常原因" name="errorType" rules={[{ required: allValues.routeType === 2 }]}>
                    <Select
                      placeholder="请选择异常原因"
                      options={getErrorrTypeName.valueList.map(v => ({ label: getErrorrTypeName(v), value: v }))}
                      disabled={allValues.routeType !== 2}
                    />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item
                    label="客户可见"
                    htmlFor={undefined}
                    name="visibleFlag"
                    getValueFromEvent={e => Number(e)}
                    rules={[{ required: true }]}
                  >
                    <Switch checkedChildren="是" unCheckedChildren="否" />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item
                    label="需跟进"
                    htmlFor={undefined}
                    name="actionFlag"
                    getValueFromEvent={e => Number(e)}
                    rules={[{ required: true }]}
                  >
                    <Switch checkedChildren="是" unCheckedChildren="否" />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
      )
    }

    const formRender1 = () => {
      return (
        <div className={styles.card}>
          <div className={styles.card_header}>中文路由描述</div>
          <div className={`${styles.card_body} ${styles.tpl}`}>
            <div className={styles.tpl_left}>
              <Form {...formProps}>
                <Row gutter={12}>
                  <Col span={12}>
                    <Form.Item label="标题" name={['routeDesc', 'titleCn']} rules={[{ required: true }]}>
                      <Input placeholder="请输入标题" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      style={{ marginBottom: 0 }}
                      label={
                        <>
                          描述<span style={{ color: token.colorTextDescription }}>{`（请用 {{}} 设置动态字段）`}</span>
                        </>
                      }
                      name={['routeDesc', 'descCn']}
                    >
                      <Input.TextArea placeholder="请输入描述" rows={4} style={{ resize: 'none' }} />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
            <div className={styles.tpl_right}>
              <DynamicField />
            </div>
          </div>
        </div>
      )
    }

    const formRender2 = () => {
      return (
        <div className={styles.card}>
          <div className={styles.card_header}>英文路由描述</div>
          <div className={`${styles.card_body} ${styles.tpl}`}>
            <div className={styles.tpl_left}>
              <Form {...formProps}>
                <Row gutter={12}>
                  <Col span={12}>
                    <Form.Item label="标题" name={['routeDesc', 'titleEn']} rules={[{ required: true }]}>
                      <Input placeholder="请输入标题" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      style={{ marginBottom: 0 }}
                      label={
                        <>
                          描述<span style={{ color: token.colorTextDescription }}>{`（请用 {{}} 设置动态字段）`}</span>
                        </>
                      }
                      name={['routeDesc', 'descEn']}
                    >
                      <Input.TextArea placeholder="请输入描述" rows={4} style={{ resize: 'none' }} />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
            <div className={styles.tpl_right}>
              <DynamicField />
            </div>
          </div>
        </div>
      )
    }

    const formRender3 = () => {
      return (
        <div className={styles.card}>
          <div className={styles.card_header}>
            <div className={styles.card_header_left}>
              <span className={styles.required_mark}>*</span>适用渠道
              <span style={{ fontWeight: 'normal' }}>（已关联{allValues.routeChannelList.length}条）</span>
            </div>
            <div className={styles.card_header_right}>
              <Button
                type="primary"
                onClick={() =>
                  AddChannelModal.open({
                    initialSelectRows: allValues.routeChannelList,
                    onChange: selectRows => form.setFieldValue('routeChannelList', selectRows),
                  })
                }
              >
                添加可用渠道
              </Button>
            </div>
          </div>
          <div className={styles.card_body}>
            <Channels data={allValues.routeChannelList} form={form} />
          </div>
        </div>
      )
    }

    return (
      <Drawer
        styles={{ header: { backgroundColor: 'var(--fba-bg)' }, body: { backgroundColor: 'var(--fba-bg)' } }}
        title={`${typeName}路由模板`}
        width={1500}
        open={open}
        onClose={onHide}
        afterOpenChange={afterOpenChange}
        footer={
          <div className={styles.footer}>
            <Space>
              <Button onClick={onHide}>取消</Button>
              <Button
                type="primary"
                disabled={fetching}
                loading={submitting}
                onClick={async () => {
                  form.submit() // 触发 scrollToFirstError
                  let values = await form.validateFields()
                  values = form.getFieldsValue(true)
                  if (!values.routeChannelList.length) {
                    return void message.error('至少要添加一条可用渠道')
                  }
                  Modal.confirm({
                    title: `确认要${actionName}吗？`,
                    onOk: async () => {
                      try {
                        setSubmitting(true)
                        const api = routeId ? apiEditTplRoute : apiAddTplRoute
                        await api(values as TSendValues)
                        message.success(`${actionName}成功`)
                        onSuccess?.()
                        onHide()
                      } finally {
                        setSubmitting(false)
                      }
                    },
                  })
                }}
              >
                {actionName}
              </Button>
            </Space>
          </div>
        }
      >
        <div className={styles.main}>
          {fetching ? (
            <Loading />
          ) : (
            <>
              <div className={styles.main_left} ref={scrollRef}>
                <section id={`${idPrefix}_0`}>{formRender0()}</section>
                <section id={`${idPrefix}_1`}>{formRender1()}</section>
                <section id={`${idPrefix}_2`}>{formRender2()}</section>
                <section id={`${idPrefix}_3`}>{formRender3()}</section>
              </div>
              <Anchor
                className={styles.main_right}
                affix={false}
                getContainer={() => scrollRef.current || window}
                onClick={e => e.preventDefault()}
                items={['基础信息', '中文路由描述', '英文路由描述', '可用渠道'].map((name, index) => ({
                  key: name,
                  href: `#${idPrefix}_${index}`,
                  title: name,
                }))}
              />
            </>
          )}
        </div>
      </Drawer>
    )
  },
  {
    open: (props: IAddOrEditTplRouteDrawerProps) => {
      updatePopup(<AddOrEditTplRouteDrawer {...props} destroy={() => updatePopup(null)} />)
    },
  },
)
